package com.google.code.gaestats;

import com.googlecode.objectify.annotation.EntitySubclass;
import org.joda.time.DateTime;
import org.joda.time.Duration;

/**
 *
 * @author JaggardM
 */
@EntitySubclass
public class PerHourCounterData extends CounterData
{
	private final static int HOURS_TO_KEEP = 8784; //24 * 366 = approximately a year

	/**
	 * Creates a new instance with an empty set of statistics and the latest time set to the beginning of this hour.
	 */
	public PerHourCounterData()
	{
		super(HOURS_TO_KEEP, new DateTime().withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0));
	}

	@Override
	protected int calculateDataPosition(DateTime time)
	{
		DateTime forHour = time.withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0);
		long hoursBeforeLatest = new Duration(forHour, latestTime).getStandardHours();
		if (hoursBeforeLatest < 0 || hoursBeforeLatest > Integer.MAX_VALUE)
		{
			//TODO: handle this error
			return -1;
		}
		return (int) hoursBeforeLatest;
	}

	@Override
	protected DateTime normalise(DateTime time)
	{
		return time.withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0);
	}

	@Override
	public StringBuilder googleJavascriptData()
	{
		StringBuilder sb = new StringBuilder("({");
		sb.append("cols: [{id: 'hour', label: 'Hour', type: 'datetime'},");
		sb.append("{id: 'sum', label: 'Sum', type: 'number'},");
		sb.append("{id: 'avg', label: 'Average', type: 'number'},");
		sb.append("{id: 'qty', label: 'Quantity', type: 'number'},");
		sb.append("{id: 'min', label: 'Minimum', type: 'number'},");
		sb.append("{id: 'max', label: 'Maximum', type: 'number'}");
		sb.append("],");
		sb.append("'rows':[");
		DateTime printTime = this.latestTime.minusHours(this.getSize());
		for (Statistics s : this)
		{
			sb.append("{c:[{v:'");
			sb.append(printTime.getMillis()); //Date
			sb.append("', f:'");
			sb.append(printTime.toString("yyyy-MM-dd hhaa"));//String Date
			sb.append("'},");
			sb.append("{v:'");
			sb.append(s.getSum());
			sb.append("'},");
			sb.append("{v:'");
			sb.append(((float)s.getSum()) / ((float)s.getQty()));
			sb.append("'},");
			sb.append("{v:'");
			sb.append(s.getQty());
			sb.append("'},");
			sb.append("{v:'");
			sb.append(s.getMin());
			sb.append("'},");
			sb.append("{v:'");
			sb.append(s.getMax());
			sb.append("'}]},");
			printTime = printTime.plusHours(1);
		}
		sb.deleteCharAt(sb.length() - 1); //Delete the last character (the comma)
		sb.append("]})");
		return sb;
	}
}
